package org.example.factory.bean;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.cache.RedisUtil;
import org.example.dto.CounterDto;
import org.example.factory.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @FileName LikeCounter
 * @Description 采用Hash数据结构进行计数
 * @Author coderfun
 * @selfDesc coding in fun
 * @date 2024-11-02
 **/
@Component
public class LikeCounter implements Counter {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private RocketMQTemplate recketMQTemplate;
    private static final Logger logger = LoggerFactory.getLogger(LikeCounter.class);
    private final static String prefix = "like";
    private final static String busi = "counter";

    @Override
    public Boolean add(CounterDto counterDto) {
        StringBuilder sb = new StringBuilder("");
        try {
            logger.info(prefix + ":add,id:{},kind:{}", counterDto.getId(), counterDto.getKind());
//            redisUtil.hIncrBy(busi + "_" + counterDto.getId(), prefix, 1);
            sb.append("HINCRBY ").append(busi + "_" + counterDto.getId()+" ").append(prefix).append(" 1");
            //发送消息到MQ
            recketMQTemplate.convertAndSend("counter", JSON.toJSONString(sb));
            logger.info("发送通知到MQ");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean sub(CounterDto counterDto) {
        try {
            logger.info(prefix + ":sub,id:{},kind:{}", counterDto.getId(), counterDto.getKind());
            String currentCountStr = (String) redisUtil.hGet(busi + "_" + counterDto.getId(), prefix);
            Integer currentCount = currentCountStr != null ? Integer.parseInt(currentCountStr) : 0;
            int newCount = currentCount - 1;
            redisUtil.hPut(busi + "_" + counterDto.getId(), prefix, String.valueOf(newCount));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer select(CounterDto counterDto) {
        try {
            logger.info(prefix + ":select,select:{},kind:{}", counterDto.getId(), counterDto.getKind());
            String currentCountStr = (String) redisUtil.hGet(busi + "_" + counterDto.getId(), prefix);
            Integer currentCount = currentCountStr != null ? Integer.parseInt(currentCountStr) : 0;
            return currentCount;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
